//
//  ProcessOrderViewController.swift
//  CJXSwiftStoryboard
//
//  Created by CJX on 2016/10/24.
//  Copyright © 2016年 caijianxi. All rights reserved.
//

import UIKit
import SwiftyJSON
import SVProgressHUD

class ProcessOrderViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,AddressViewControllerDelegate,PaySelectViewControllerDelegate,ShippingViewControllerDelegate {

    var allPrice : String?
    var cartArray : NSMutableArray?
    var dic : NSDictionary?
    
    
    
    var myTableView = UITableView(frame: CGRect(x: 0, y: 64, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*0.94-64), style: .grouped)
    let PROCESSCELL = "ProcessOrderCell"
    let CELL = "THIRDCELL"
    
    var payMethodLabel = UILabel()
    var shippingLabel = UILabel()
    
    var codeTextField = UITextField()
    
    var model : AddressModel?
    var paySelectDic = NSDictionary()
    var shippingDic = NSDictionary()
    
    
    var totalPrice : String?
    
    
    let descriptArray = ["Subtotal:","Shipping:","Total:"]
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.creatNavView()
        self.creatTabelView()
        self.creatCheckoutView()
        
        

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}

extension ProcessOrderViewController{
    fileprivate func creatNavView(){
//        print(cartArray)
//        print(allPrice!)
//        print("dic>>>>>"+String(dic))
        
        self.view.backgroundColor = UIColor.white
        self.automaticallyAdjustsScrollViewInsets = false
        self.title = "Process Order"
        
        let leftBtn = UIButton(type: .custom)
        leftBtn.setImage(UIImage(named: "nav_back"), for: UIControlState())
        leftBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        leftBtn.addTarget(self, action: #selector(leftBtnClick), for: .touchUpInside)
        let item = UIBarButtonItem(customView: leftBtn)
        self.navigationItem.leftBarButtonItem = item
        
        
        let rightItemCustomeView   = UIButton(type: UIButtonType.custom)
        rightItemCustomeView.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        rightItemCustomeView.setImage(UIImage(named:"nav_close"), for: UIControlState())
        rightItemCustomeView.addTarget(self, action: #selector(rightBtnClick), for: UIControlEvents.touchUpInside)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightItemCustomeView);
        
        
    }
    
    func leftBtnClick(){
        self.navigationController?.popViewController(animated: true)
    }
    
    func rightBtnClick(){
        self.navigationController?.popToRootViewController(animated: true)
    }
}

extension ProcessOrderViewController{
    
    fileprivate func creatTabelView(){
        myTableView.delegate = self
        myTableView.dataSource = self
        self.view.addSubview(myTableView)
        myTableView.register(ProcessSubTitleTableViewCell.self, forCellReuseIdentifier: CELL)
        let nib = UINib(nibName: "ProcessOrderTableViewCell", bundle: nil)
        myTableView.register(nib, forCellReuseIdentifier: PROCESSCELL)
        
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 4
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 3 {
            return 3
        }else if section == 0 {
            return (self.cartArray?.count)!
        }else{
            return 0
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: PROCESSCELL)
            let model = self.cartArray![indexPath.row] as? ShoppingCartModel
            
            (cell as? ProcessOrderTableViewCell)?.model = model
            cell?.selectionStyle = .none
            
            return cell!
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: CELL)
            cell?.selectionStyle = .none
            
            (cell as? ProcessSubTitleTableViewCell)?.descriptLabel.text = self.descriptArray[indexPath.row]
            
            if indexPath.row == 0 {
                (cell as? ProcessSubTitleTableViewCell)?.moneyLabel.text = self.allPrice!

            }else if indexPath.row == 1 {
                if (shippingDic.allKeys as? NSArray)!.count == 0{
                    (cell as? ProcessSubTitleTableViewCell)?.moneyLabel.text = ""
                }else{
                    (cell as? ProcessSubTitleTableViewCell)?.moneyLabel.text = shippingDic["cost"]as?String
                }
                

            }else{
                if (shippingDic.allKeys as? NSArray)!.count == 0{
                     (cell as? ProcessSubTitleTableViewCell)?.moneyLabel.text = self.allPrice!
                }else{
                    let a = self.stringByReplaceWithStr(self.allPrice!)
                    let b = self.stringByReplaceWithStr(String(describing: shippingDic["cost"]!))
                    let totalPrice = a + b
                    
                    
                     (cell as? ProcessSubTitleTableViewCell)?.moneyLabel.text = self.stringWithMoney() + String(format: "%.2f",totalPrice)
                }

            }
            
            return cell!
            
        }
       
        
    }
    
    func stringByReplaceWithStr(_ str:String) -> Float{
        let num = str.replacingOccurrences(of: "$", with: "").replacingOccurrences(of: ",", with: "").replacingOccurrences(of: "CAD", with: "").replacingOccurrences(of: "£", with: "").replacingOccurrences(of: "AU", with: "").replacingOccurrences(of: "€", with: "")
        
        return Float(num)!
    }
    
    func stringWithMoney() -> String{
        var str = ""
        let moneyStr = UserDefaults.standard.object(forKey: "MONEYINDEX") as? String
        var index = 0
        
        if moneyStr == nil || moneyStr == "" {
            index = 1
        }else{
            index = Int(moneyStr!)!
        }
        
        
        if index == 0 {
            str = "CAD$"
        }else if index == 1{
            str = "$"
        }else if index == 2{
            str = "£"
        }else if index == 3{
            str = "AU$"
        }else{
            str = "€"
        }
        
        return str
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let head = UIView()
        head.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*0.1)
        head.backgroundColor = UIColor.white
        
        if section == 0 {
            let headerView = UIView()
            headerView.frame = CGRect( x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*0.2)
            headerView.backgroundColor = UIColor.white
            
            let imgView = UIImageView()
            imgView.frame = CGRect( x: 0, y: SCREEN_HEIGHT * 0.02, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*0.15)
            imgView.image = UIImage(named: "topBackView2")
            headerView.addSubview(imgView)
            
            if model == nil {
                let descriptLabel = UILabel()
                descriptLabel.text = "Please Choose Shipping Address"
                descriptLabel.font = UIFont.systemFont(ofSize: 12)
                descriptLabel.textColor = UIColor.gray
                descriptLabel.frame = CGRect( x: SCREEN_WIDTH*0.1, y: SCREEN_HEIGHT*0.03, width: SCREEN_WIDTH*0.8, height: SCREEN_HEIGHT*0.13)
                headerView.addSubview(descriptLabel)
            }else{
                let lastNameLabel = UILabel()
                lastNameLabel.frame = CGRect(x: SCREEN_WIDTH*0.1, y: SCREEN_HEIGHT*0.02+10, width: SCREEN_WIDTH*0.4, height: SCREEN_HEIGHT*0.03)
                lastNameLabel.text = model?.lastname
                lastNameLabel.font = UIFont.systemFont(ofSize: 14)
                headerView.addSubview(lastNameLabel)
                
                let codeLabel = UILabel()
                codeLabel.frame = CGRect(x: SCREEN_WIDTH*0.6, y: SCREEN_HEIGHT*0.02+10, width: SCREEN_WIDTH*0.4, height: SCREEN_HEIGHT*0.03)
                codeLabel.text = model?.postcode
                codeLabel.font = UIFont.systemFont(ofSize: 14)
                headerView.addSubview(codeLabel)
                
                let phoneLabel = UILabel()
                phoneLabel.frame = CGRect(x: SCREEN_WIDTH*0.1, y: SCREEN_HEIGHT*0.05+10, width: SCREEN_WIDTH*0.8, height: SCREEN_HEIGHT*0.03)
                phoneLabel.text = model?.telephone
                phoneLabel.font = UIFont.systemFont(ofSize: 14)
                headerView.addSubview(phoneLabel)
                
                let addressLabel = UILabel()
                addressLabel.frame = CGRect(x: SCREEN_WIDTH*0.1, y: SCREEN_HEIGHT*0.08+10, width: SCREEN_WIDTH*0.8, height: SCREEN_HEIGHT*0.07-20)
                addressLabel.text = (model?.street_address)! + "  " + (model?.state)! + "  " + (model?.country_name)!
                addressLabel.font = UIFont.systemFont(ofSize: 14)
                addressLabel.numberOfLines = 0
                headerView.addSubview(addressLabel)
                
            }
            
            
            
            let titleLabel = UILabel()
            titleLabel.frame = CGRect(x: 20, y: SCREEN_HEIGHT*0.17, width: SCREEN_WIDTH-40, height: SCREEN_HEIGHT*0.05)
            titleLabel.text = "Product List"
            headerView.addSubview(titleLabel)
            
            let tap = UITapGestureRecognizer(target: self, action: #selector(headerViewClick))
            headerView.addGestureRecognizer(tap)
            
            
            return headerView
        }else if section == 1{
            
            payMethodLabel.frame = CGRect(x: 20, y: 0, width: SCREEN_WIDTH-40, height: SCREEN_HEIGHT*0.08)
            if (paySelectDic.allKeys as? NSArray)!.count == 0 {
                payMethodLabel.text = "Please choose pay method:"
            }else{
                payMethodLabel.text = "Pay Method:  " + String(describing: paySelectDic["title"]!)
            }
            
            payMethodLabel.font = UIFont.systemFont(ofSize: 14)
            head.addSubview(payMethodLabel)
            
            let tap = UITapGestureRecognizer(target: self, action: #selector(secondHeaderClick))
            head.addGestureRecognizer(tap)
            return head
            
        }else if section == 2{
            
            shippingLabel.frame = CGRect(x: 20, y: 0, width: SCREEN_WIDTH-40, height: SCREEN_HEIGHT*0.08)
            shippingLabel.numberOfLines = 0
            shippingLabel.font = UIFont.systemFont(ofSize: 14)
            if (shippingDic.allKeys as? NSArray)!.count == 0{
                shippingLabel.text = "Shipping:Free shipping.(You can change ship,please click here.)"
            }else{
                shippingLabel.text = "Shipping:   " + String(describing: shippingDic["title"]!)
            }
            
            head.addSubview(shippingLabel)
            
            let tap = UITapGestureRecognizer(target: self, action: #selector(thirdHeaderClick))
            head.addGestureRecognizer(tap)
            
            return head
        }else if section == 3{
            
            codeTextField.frame = CGRect(x: 20, y: SCREEN_HEIGHT*0.01, width: SCREEN_WIDTH*0.6, height: SCREEN_HEIGHT*0.06)
            codeTextField.placeholder = "CODE"
            head.addSubview(codeTextField)
            
            let applyBtn = UIButton(type: .custom)
            applyBtn.frame = CGRect(x: SCREEN_WIDTH*0.8 - 20, y: SCREEN_HEIGHT*0.01, width: SCREEN_WIDTH*0.2, height: SCREEN_HEIGHT*0.06)
            applyBtn.setTitle("Apply", for: UIControlState())
            applyBtn.setTitleColor(UIColor.white, for: UIControlState())
            applyBtn.backgroundColor = UIColor.darkGray
            applyBtn.addTarget(self, action: #selector(fourthBtnClick), for: .touchUpInside)
            head.addSubview(applyBtn)
            
            
            return head
        }else{
            return nil
        }
        
    }
    
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            
            return SCREEN_HEIGHT * 0.22
        }else {
            return SCREEN_HEIGHT * 0.08
            
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return SCREEN_HEIGHT * 0.2
        }else{
            return SCREEN_HEIGHT * 0.08
        }
    }
    
    
    
//    第一个区头点击方法
    func headerViewClick(){
        let addressVC = AddressViewController()
        addressVC.delegate = self
        self.navigationController?.pushViewController(addressVC, animated: true)

    }
    func giveTheAddressToProcessOrderVC(_ dataArr: AddressModel) {
        
        model = dataArr
        self.transMethodSelector()
        self.myTableView.reloadData()
    }
    
    func transMethodSelector(){
        let urlStr = APIBASE + "main_page=checkout_shipping"
        
        let parma = ["shipping":"table_table","address_book_id":model!.address_book_id!,"zenid":UserSession.shareInstance.cookie!]
        NetworkTool.shareInstance.request(.post, urlString: urlStr, parmas: parma as [String : NSObject]) { (result, error) in
            if result != nil{
//                print(result)
            }else{
                SVProgressHUD.showError(withStatus: "shipping error:" + String(describing: error))
                print("shipping error:" + String(describing: error))
            }
        }
        
        
    }
    //    第二个区头点击方法
    func secondHeaderClick(){
        let paySelectVC = PaySelectViewController()
        paySelectVC.delegate = self
        self.navigationController?.pushViewController(paySelectVC, animated: true)
    }
    func paySelectMethodWithDic(_ dict: NSDictionary) {
        
        paySelectDic = dict
        self.myTableView.reloadData()
    }
//    第三个区头点击方法
    func thirdHeaderClick(){
        let shippingVC = ShippingViewController()
        shippingVC.delegate = self
        self.navigationController?.pushViewController(shippingVC, animated: true)
    }
    
    func giveTheShippingDataToProcessOrderVC(_ id: String, title: String, cost: String) {
        
        let dic = ["id":id,"title":title,"cost":cost]
        shippingDic = dic as NSDictionary
        
        self.myTableView.reloadData()
    }
//    第四个区头按钮点击方法
    func fourthBtnClick(){
        let urlStr = APIBASE + "main_page=checkout_payment"
        let parma = ["payment":"cp_pay","dc_redeem_code":self.codeTextField.text!,"zenid":UserSession.shareInstance.cookie!]
        NetworkTool.shareInstance.request(.post, urlString: urlStr, parmas: parma as [String : NSObject]) { (result, error) in
            if result != nil{
//                let json = JSON(result!)
//                print(json)
                SVProgressHUD.showSuccess(withStatus: "Enter successfully!")
            }else{
                SVProgressHUD.showError(withStatus: "postcode error:" + String(describing: error))
                print("postcode error:" + String(describing: error))
            }
        }
        
    }
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
}


extension ProcessOrderViewController{
    fileprivate func creatCheckoutView(){
        
        let checkoutBtn = UIButton(type: .custom)
        checkoutBtn.frame = CGRect(x: 0, y: SCREEN_HEIGHT*0.94, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*0.06)
        checkoutBtn.setTitle("Checkout", for: UIControlState())
        checkoutBtn.setTitleColor(UIColor.white, for: UIControlState())

        checkoutBtn.backgroundColor = UIColor.black
        checkoutBtn.addTarget(self, action: #selector(chectoutBtnClick), for: .touchUpInside)
        self.view.addSubview(checkoutBtn)
        
        
    }
    
    
    func chectoutBtnClick(){
        if model == nil {
            SVProgressHUD.showInfo(withStatus: "Please Choose Shipping Address!")
            return
        }
        
        if (paySelectDic.allKeys as? NSArray)!.count == 0 {
            SVProgressHUD.showInfo(withStatus: "Please Choose Pay Method!")
            return
        }
        
        if (shippingDic.allKeys as? NSArray)!.count == 0{
            SVProgressHUD.showInfo(withStatus: "Please Choose Shipping Method!")
            return
        }
        
        var parma : [String:NSObject]?
        
        let urlStr = APIBASE + "main_page=checkout_payment"
        
        if self.codeTextField.text == nil || self.codeTextField.text == "" {
            parma = ["act":"set_payment" as NSObject,"payment":(self.paySelectDic["id"] as? String)! as NSObject,"zenid":UserSession.shareInstance.cookie! as NSObject]
            
        }else{
            parma = ["act":"apply_coupon" as NSObject,"payment":(self.paySelectDic["id"] as? String)! as NSObject,"dc_redeem_code":self.codeTextField.text! as NSObject,"zenid":UserSession.shareInstance.cookie! as NSObject]
        }
        
        NetworkTool.shareInstance.request(.post, urlString: urlStr, parmas: parma!) { (result, error) in
            if result != nil{
//                let json = JSON(result!)
//                print(json)
                
                let dic = result as? NSDictionary
                let number = String(describing: dic!["status"]!)
                print(number)
                if number == "1"{
                    let dataDic = dic!["data"]as?NSDictionary
                    let arr = dataDic!["order_total"]as?[[String:NSObject]]
                    for shipDictionary in arr!{
                        
                        if String(describing: shipDictionary["code"]!) == "ot_total"{
                            
                            self.totalPrice = shipDictionary["text"]as?String
                        }
                    }
                    
                    let payVC = PayViewController()
                    payVC.allPrice = self.totalPrice!
                    
                    self.navigationController?.pushViewController(payVC, animated: true)
                    
                }else{
                    SVProgressHUD.showInfo(withStatus: String(describing: dic!["status_message"]))
                }
                
            }else{
                SVProgressHUD.showError(withStatus: "checkout error:" + String(describing: error))
                print("checkout error:" + String(describing: error))
            }
        }
    }
}













